package dao_test;

import java.io.IOException;
import java.rmi.AlreadyBoundException;
import java.util.List;

import junit.framework.Assert;

import model.Vokabel;

import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.junit.Before;
import org.junit.Test;

import xml.Dom4JFileReader;

import dao.VokabelDao;
import dao.VokabelDaoImpl;

public class VokabelDaoImplTest
{
	

	
	private Vokabel v1 = new Vokabel("gehen", "to run", 1, 1);
	private Vokabel v2 = new Vokabel("schlafen", "to sleep", 2, 2);
	private Vokabel v3 = new Vokabel("nacht", "night", 3, 3);
	private Vokabel v4 = new Vokabel("tag", "day", 2, 2);
	
	private String path = "src-test-resources\\testwriter.xml";
	private VokabelDaoImpl dao;// = new VokabelDaoImpl(path);
	
	private Dom4JFileReader reader;// = new Dom4JFileReader();
	
	@Before
	public void starten()
	{
		
		dao  = new VokabelDaoImpl(path);
		reader =  new Dom4JFileReader();
		
	}
	
	@Test
	public void insertElement() throws IOException, DocumentException, AlreadyBoundException
	{
		v1.setId("1");
		dao.insertElement(v1);
		List<Element> list = readXml();
		Assert.assertNotNull(list);
		Assert.assertEquals(1, list.size());
		Assert.assertEquals("gehen", list.get(0).elementText("german"));
		
		v2.setId("2");
		dao.insertElement(v2);
		list = readXml();
		Assert.assertNotNull(list);
		Assert.assertEquals(2, list.size());
		Assert.assertEquals("schlafen", list.get(1).elementText("german"));
		
		v3.setId("3");
		dao.insertElement(v3);
		list = readXml();
		Assert.assertNotNull(list);
		Assert.assertEquals(3, list.size());
		Assert.assertEquals("nacht", list.get(2).elementText("german"));
		
		v4.setId("4");
		dao.insertElement(v4);
		list = readXml();
		Assert.assertNotNull(list);
		Assert.assertEquals(4, list.size());
		Assert.assertEquals("tag", list.get(3).elementText("german"));
		
	}
	
	
	@Test
	public void removeVokable() throws AlreadyBoundException, IOException, DocumentException
	{
		
		v2.setId("2");
		dao.remove(v2);
		List<Element> list = readXml();
		Assert.assertNotNull(list);
		Assert.assertEquals(3, list.size());
	}
	

	@Test
	public void updateElement() throws AlreadyBoundException, IOException, DocumentException
	{
		v3.setId("3");
		v3.raiseLvlEnglish();
		dao.update( v3 );
		List<Element> list = readXml();
		for ( Element e : list)
			if(e.attributeValue( "id" ).equals( "3" ))
				Assert.assertEquals( "4" , e.element( "lvlEnglish" ).attributeValue( "lvl" ) );
		
	}

	@Test
	public void getAllVokabelFromXml() throws AlreadyBoundException
	{
		List<Vokabel> list = dao.getAllVokabelFromXml();
		Assert.assertEquals( 3 , list.size() );
		Assert.assertEquals( "night" , list.get( 1 ).getEnglish() );
	}
	
	public List<Element> readXml() throws DocumentException, IOException
	{
		return reader.readDocument(path).getRootElement().elements("vokabel");
		
	}
	
	
}
